<template>
  <div class="run-modal-style">
    <Form :model="modelForm" ref="resourceForm" :rules="rules" :label-width="80">
      <Row :gutter="20" class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item :label="$t('module.resourceManage.resCode')" prop="resourceCode">
            <Input
              v-model="modelForm.resourceCode"
              :data="searchResult"
              @on-change="onChange"
              @on-select="onSelectSearch"
              @on-clear="onClear"
              :placeholder="$t('module.resourceManage.enterCode')"
              :disabled="!isAdd"
              clearable
            ></Input>
          </Form-item>
        </Col>
       
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item :label="$t('module.resourceManage.resName')" prop="resourceName">
            <Input
              v-model="modelForm.resourceName"
              
              :disabled="isSelected"
              :placeholder="$t('module.resourceManage.enterName')"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item :label="$t('module.resourceManage.resourceType')" prop="resourceType">
            <Select
              v-model="modelForm.resourceType"
              :transfer="true"
              
              :disabled="!isAdd"
            >
              <Option :value="1" :key="1">{{$t('module.resourceManage.uiResource')}}</Option>
              <Option :value="2" :key="2">{{$t('module.resourceManage.apiResource')}}</Option>
              <Option :value="3" :key="3">{{$t('module.resourceManage.FlowableModelResource')}}</Option>
            </Select>
          </Form-item>
        </Col>
        
      </Row>
      <!-- 父级UI资源和是否公开 切换显示 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item :label="$t('module.valueSet.ownnerapp')" prop="applicationId">
            <Input placeholder v-model="applicationList[applicationId]"  disabled></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;" v-if="modelForm.resourceType == 1">
          <Form-item :label="$t('module.resourceManage.parentUI')" prop="parentUI">
            <!-- <Select
              :placeholder="$t('module.resourceManage.selectParentUI')"
              v-model="modelForm.parentResourceId"
              :transfer="true"
              
              :disabled="isSelected"
              clearable
            >
              <Option
                v-for="item in partantResource"
                :value="item.id"
                :key="item.id"
              >{{item.resourceName}}</Option>
            </Select> -->
            <div style="display: flex;">
              <Input
                v-model="modelForm.parentResourceName"
                :placeholder="$t('module.resourceManage.selectParentUI')"
                :disabled="true"
              />
              <RPButton style="margin-left: 10px;" optType="reset" text="选择" @click="selectParentUI" />
            </div>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;" v-if="modelForm.resourceType == 2">
          <Form-item :label="$t('module.valueSet.isPublic')" prop="publicFlag">
            <RadioGroup v-model="modelForm.publicFlag" >
              <Radio :label="1" :disabled="isSelected">
                <span>{{this.$t("module.valueSet.public")}}</span>
              </Radio>
              <Radio :label="2" :disabled="isOnlyPublic || isSelected">
                <span>{{this.$t("module.valueSet.notpublic")}}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item :label="$t('common.status')" prop="enabled">
            <RadioGroup v-model="modelForm.enabled" >
              <Radio :label="1" :disabled="isSelected">{{$t('common.enable')}}</Radio>
              <Radio :label="0" :disabled="isSelected">{{$t('common.disable')}}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="resourceDesc" :label="$t('module.resourceManage.description')">
            <Input
              v-model="modelForm.resourceDesc"
              type="textarea"
              :rows="4"
              :placeholder="$t('module.resourceManage.enterDesc')"
            ></Input>
          </Form-item>
        </Col>
      </Row>

<!--      权限模型-->
      <Row :gutter="32" class="code-row-bg" v-if="modelForm.resourceType == 2">
        <Col span="24">
          <Form-item prop="authType" :label="$t('module.resourceManage.permissionModel')">
            <Select
              v-model="modelForm.authType"
              :transfer="true"
              
            >
              <Option
                v-for="item in permissionModelList"
                :value="item.vsiKey" :key="item.vsiKey">{{item.vsiValue}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
<!--认证地址-->
      <Row :gutter="32" class="code-row-bg" v-if="modelForm.authType ==='2'">
        <Col span="24">
          <Form-item prop="authUrl" :label="$t('module.resourceManage.authenticationAddress')">
            <Input
              v-model="modelForm.authUrl"
              type="text"
              maxlength="100"
              :placeholder="$t('module.resourceManage.authenticationAddressDesc')"
            ></Input>
          </Form-item>
        </Col>
        <Col span="24">
          <div class="url_desc">
            <p><Icon type="ios-information-circle-outline" color="#515a6e" size="18px"/>认证地址需满足以下三个条件</p>
            <p>1. post请求的接口；</p>
            <p>2. 通过body接收参数；</p>
            <p>3. http状态码，有权限返回200，无权限返回401</p>
          </div>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import SelectParentUIResource from './SelectParentUIResource.vue'
import { updateResource, addResource, queryResouceListForCode, getParentUi } from "@/api/resourceApi.js";
import { getValueSetByCode } from "@/api/configApi";
import locales from "./locales.js";
import { searchDelayTime } from "@/const.js";
import { resourceCodeReg } from "@/const.js";

export default {
  name: "ResourceEdit",
  mixins: [locales],
  props: {
    functionForm: {
      type: Object,
      default() {
        return {};
      }
    },
    applicationList: {
      type: Object,
      default() {
        return {};
      }
    },
    isAdd: {
      type: Boolean,
      default() {
        return true;
      }
    },
    applicationId: {
      type: String,
      default() {
        return "";
      }
    },
    applicationName: {
      type: String,
      default() {
        return "";
      }
    },
    functionId: {
      type: String,
      default() {
        return "";
      }
    },
    id: {
      type: String,
      default() {
        return "";
      }
    },
    parentResourceId: {
      type: String,
      default() {
        return "";
      }
    },
    resourceObj: {
      type: Object,
      default() {
        return null;
      }
    },
    canCreateUI: {
      type: Boolean,
      default() {
        return true;
      }
    },
    canCreateAPI: {
      type: Boolean,
      default() {
        return true;
      }
    },
    canCreateFunc: {
      type: Boolean,
      default() {
        return true;
      }
    },
    isOnlyPublic: {
      type: Boolean,
      default() {
        return false;
      }
    },
    permissionModelList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validateResourceCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.resourceManage.enterCode")));
      } else if (value.length > 128) {
        callback(new Error(this.$t("module.resourceManage.resCodeMaxFifty")));
      } else if (!this.isSelected && this.isResourceCodeExist) {
        callback(new Error(this.$t("module.resourceManage.resourceCodeTip")));
      } else if (value != value.trim()) {
        callback(new Error(this.$t("module.resourceManage.resCodeNoBlank")));
      } else if (!new RegExp(resourceCodeReg).test(value)) {
        callback(new Error(this.$t("module.resourceManage.resCodeCheck")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("module.resourceManage.resCodeCheck")));
      }
      // 资源编码自动转大写
      this.modelForm.resourceCode = this.modelForm.resourceCode.toUpperCase();
      callback();
    };
    const validateResourceName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.resourceManage.enterName")));
      } else if (value != value.trim()) {
        callback(new Error(this.$t("module.resourceManage.noBlank")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.resourceManage.resNameMaxFifty")));
      }
      callback();
    };
    return {
      status: [
        { id: 0, effect: "有效" },
        { id: 1, effect: "无效" },
        { id: 3, effect: "全部" }
      ],
      partantResource: [],
      modelForm: {
        id: this.id,
        applicationId: this.applicationId,
        functionId: this.functionForm.functionId,
        parentResourceId: this.parentResourceId,
        resourceCode: "",
        resourceName: "",
        resourceType: 0,
        publicFlag: this.isOnlyPublic ? 1 : 2,
        enabled: 1,
        resourceDesc: "",
        parentResourceName: "",
        parentResourceCode: "",
        authType: "1",
        authUrl: ""
      },
      rules: {
        resourceCode: [{ validator: validateResourceCode, trigger: "blur", required: true }],
        resourceName: [{ validator: validateResourceName, trigger: "blur", required: true }],
        authType: [{ trigger: "blur", required: true, message: this.$t('module.resourceManage.permissionModelDesc') }],
        authUrl: [
          { trigger: "blur", required: true, message: this.$t('module.resourceManage.authenticationAddressDesc') },
/*          {
            pattern: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/,
            trigger: 'blur',
            message: this.$t('module.resourceManage.authenticationAddressDescCorrect')
          },*/
        ],
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      searchValue: "",
      searchResult: [],
      searchResultResource: [],
      selectedResource: null,
      pressCount: 0,
      isSelected: false,
      isResourceCodeExist: false
    };
  },
  created: function() {
    this.init();
    if (this.id) {
      this.$emit("SetTitle", this.$t("module.resourceManage.editRes"));
    } else {
      this.$emit("SetTitle", this.$t("module.resourceManage.creatRes"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    init() {
      if (this.resourceObj != null) {
        this.modelForm.resourceCode = this.resourceObj.resourceCode;
        this.modelForm.resourceName = this.resourceObj.resourceName;
        this.modelForm.resourceType = this.resourceObj.resourceType;
        this.modelForm.publicFlag = this.resourceObj.publicFlag;
        this.modelForm.enabled = this.resourceObj.enabled;
        this.modelForm.resourceDesc = this.resourceObj.resourceDesc;
        this.modelForm.parentResourceName = this.resourceObj.parentResourceName
        this.modelForm.authType = this.resourceObj.authType + ""
        this.modelForm.authUrl = this.resourceObj.authUrl
        // 获取当前资源下的父UI资源
        let data = {
          applicationId: this.applicationId,
          functionId: this.functionForm.id,
          exId: this.resourceObj.id,
          resourceTypes: [this.resourceObj.resourceType]
        };
        getParentUi(data).then(res => {
          this.partantResource = res.data;
        });
      } else if (this.canCreateUI) {
        this.modelForm.resourceType = 1;
        let data = {
          applicationId: this.applicationId,
          functionId: this.functionForm.id,
          resourceTypes: [this.modelForm.resourceType]
        };
        getParentUi(data).then(res => {
          this.partantResource = res.data;
        });
      } else if (this.canCreateAPI) {
        this.modelForm.resourceType = 2;
      } else {
        this.modelForm.resourceType = 3;
      }
    },
    save() {
      this.$refs["resourceForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (!this.isAdd) {
            updateResource(this.modelForm)
              .then(response => {
                this.$message.success({
                  content: this.$t("module.resourceManage.editSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            addResource(this.modelForm)
              .then(response => {
                this.$message.success({
                  content: this.$t("module.resourceManage.createSuccess"),
                  duration: 3
                });
                this.modelForm.id = response.data;
                this.$emit("Close", this.modelForm);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
        }
      });
    },
    onChange(value) {
      if (value) {
        // 改变选择的资源时
        if (this.selectedResource && this.selectedResource.resourceCode != value) {
          // 清空选择的资源
          this.isSelected = false;
          this.selectedResource = null;
        }
      } else {
        // 清空时
        this.onClear();
      }
    },
    onSearch(value) {
      console.log("in onSearch " + value);
      // 编辑时不查询已有资源
      if (this.id) {
        return;
      }
      // 能创建API资源时才进行查询
      if (!this.canCreateAPI) {
        return;
      }
      this.searchResult = [];
      // 选择结果不再查询
      if (value && this.isSelected && this.selectedResource && this.selectedResource.resourceCode == value) {
        return;
      }

      this.isResourceCodeExist = false;
      if (value) {
        this.pressCount++;
        let param = {
          applicationId: this.applicationId,
          resourceCode: value,
          resourceType: 2,
          size: 10
        };
        // 延时查询
        setTimeout(() => {
          if (this.pressCount == 1) {
            this.pressCount = 0;
            // this.isShowSpin = true;
            // this.searchHint = "查询中...";
            queryResouceListForCode(param).then(({ data: records }) => {
              this.searchResultResource = records;
              if (records.length > 0) {
                // this.isShowSpin = false;
                // this.searchHint = "";
                records.forEach(resource => {
                  if (value == resource.resourceCode) {
                    this.$Modal.confirm({
                      title: this.$t("module.resourceManage.reuseResources"),
                      content: this.$t("module.resourceManage.reuseResourcesContent"),
                      onOk: () => {
                        this.onSelectSearch(value, true);
                      },
                      onCancel: () => {
                        this.isResourceCodeExist = true;
                        this.$refs["resourceForm"].validateField("resourceCode");
                      }
                    });
                  }
                  this.searchResult.push(resource.resourceCode);
                });
              } else {
                // this.isShowSpin = true;
                // this.searchHint = "无查询结果";
              }
            });
          } else {
            this.pressCount--;
          }
        }, searchDelayTime);
      }
    },
    onSelectSearch(value, isInput) {
      console.log("in onSelectSearch " + value);
      if (!isInput) {
        this.$message.error({
          content: this.$t("module.resourceManage.selectResourceContent"),
          duration: 5
        });
      }
      this.isSelected = true;
      this.selectedResource = this.searchResultResource.find(resource => {
        return resource.resourceCode == value;
      });
      // 表单设值
      this.modelForm.resourceCode = this.selectedResource.resourceCode;
      this.modelForm.resourceName = this.selectedResource.resourceName;
      this.modelForm.resourceType = this.selectedResource.resourceType;
      this.modelForm.publicFlag = this.selectedResource.publicFlag;
      this.modelForm.enabled = this.selectedResource.enabled;
      // 校验
      this.$refs["resourceForm"].validate();
    },
    onClear(value) {
      console.log("in onClear " + value);
      // 清空查询结果
      this.searchResult = [];
      this.searchResultResource = [];
      // 清空选择的资源
      this.isSelected = false;
      this.selectedResource = null;
    },
    selectParentUI() {
      new this.$pageModal(
        SelectParentUIResource,
        {
          props: {
            tenantCode: this.tenantCode,
            applicationId: this.applicationId,
            functionForm: this.functionForm,
            resourceObj: this.resourceObj,
            canCreateUI: this.canCreateUI
          }
        },
        data => {
          if (data) {
            console.log(888888, data)
            this.modelForm.parentResourceId = data.id
            this.modelForm.parentResourceCode = data.code
            this.modelForm.parentResourceName = data.name
          }
        }
      )
    }
  },
  watch: {},
  directives: {}
};
</script>

<style lang="less">
.url_desc{
  background: #fef3e5;
  border: 1px solid #face93;
  border-radius: 6px;
  margin-left: 15px;
  padding: 10px;
  font-size: 12px;
  i{
    font-weight: bold;
    font-size: 18px;
    margin-right: 6px;
  }
  p:not(:nth-child(1)){
    padding-left: 20px;
  }
}
</style>
